/**
 * 用户登录注册页面
 */
import Taro from '@tarojs/taro';
import React, { useState } from 'react';
import { View, Text, Input, Button, Image } from '@tarojs/components';

import { getUserInfo } from '../../api/user';
import { routerBack } from '../../contexts/store';
import { IMAGE_BASE_URL } from '../../utils/common';
import { useAppContext } from '../../contexts/AppContext';
import { 
  sendPhoneCode, loginWithPhone, loginWithPassword, 
  wechatLogin, registerUser, getWechatUserInfoApi, coachRegisterApi
} from '../../api/auth';

import './index.scss';


const LoginPage: React.FC = () => {
  const [code, setCode] = useState('');
  const [phone, setPhone] = useState('');
  const { userInfo, setUserInfo } = useAppContext();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [countdown, setCountdown] = useState<number>(0);
  const [codeValid, setCodeValid] = useState<string>('');
  const [usernameValid, setUsernameValid] = useState('');
  const [phoneValid, setPhoneValid] = useState<string>('');
  const [isSendingCode, setIsSendingCode] = useState(false);
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordValid, setPasswordValid] = useState<string>('');
  const [confirmPasswordValid, setConfirmPasswordValid] = useState('');
  const [isLoginLoading, setIsLoginLoading] = useState<boolean>(false);
  const [pageType, setPageType] = useState<'login' | 'register'>('login');
  const [loginType, setLoginType] = useState<'phone' | 'password'>('phone');
  const [registerType, setRegisterType] = useState<'student' | 'coach'>('student');

  /**
   * 发送手机验证码
   */
  const handleSendCode = async () => {
    if (!/^1[0-9]\d{9}$/.test(phone)) {
      setPhoneValid('请输入11位有效的手机号');
      if (Taro && typeof Taro.showToast === 'function') {
        Taro.showToast({
          title: '请输入有效的手机号',
          icon: 'none'
        });
      }
      return;
    }
    setPhoneValid('');
    if (isSendingCode) {
      return;
    }

    try {
      setIsSendingCode(true);
      const success = await sendPhoneCode(phone);
      if (success) {
        if (Taro && typeof Taro.showToast === 'function') {
          Taro.showToast({
            title: '验证码发送成功',
            icon: 'success'
          });
        }
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown(prev => {
            if (prev <= 1) {
              clearInterval(timer);
              setIsSendingCode(false);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        Taro.showToast({
          title: '发送验证码失败，请重试',
          icon: 'none'
        });
        setIsSendingCode(false);
      }
    } catch (error) {
      console.error('发送验证码失败:', error);
      Taro.showToast({
        title: '发送验证码失败，请重试',
        icon: 'none'
      });
      setIsSendingCode(false);
    }
  };

  /**
   * 手机号验证码登录
   */
  const handleUserLogin = async () => {
    if (!phone) {
      setPhoneValid('请输入手机号');
      return;
    }
    setPhoneValid('');
    let loginApi: any = null;
    let value = '';
    if (loginType == 'phone') {
      if (!code) {
        setCodeValid('请输入验证码');
        return;
      }
      setCodeValid('');
      value = code;
      loginApi = loginWithPhone;
    } else {
      if (!password) {
        setPasswordValid('请输入密码');
        return;
      }
      setPasswordValid('');
      value = password;
      loginApi = loginWithPassword;
    }

    try {
      setIsLoginLoading(true);
      const res = await loginApi(phone, value);
      if (res.code == 200) {
        await getUserInfo().then((userInfoResponse) => {
          if (userInfoResponse.code === 200 && userInfoResponse.data) {
            console.log("更新用户信息");
            setUserInfo({ ...userInfoResponse.data, updateTime: new Date().getTime() });
            Taro.showToast({
              title: '登录成功,欢迎您~',
              icon: 'success'
            });
            routerBack(userInfoResponse.data);
          }
        })

      } else {
        if (res.code == 10001) {
          Taro.showModal({
            title: '当前手机号尚未注册成为用户',
            content: '请选择您的注册身份',
            confirmText: '学员注册',
            cancelText: '教练注册',
            cancelColor: '#1890ff',
            confirmColor: '#ff4757',
            success: (res) => {
              if (res.confirm) {
                setPageType('register');
              }else{
                Taro.redirectTo({
                  url: `/pages/coach-register/index?phone=${phone}`,
                });
              }
            }
          })
        }else{
          // 根据登录方式设置对应的错误信息
          if (loginType === 'phone') {
            setCodeValid(res.message);
          } else {
            setPasswordValid(res.message);
          }
          Taro.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          });
        }
      }
    } catch (error) {
      console.error('登录失败:', error);
      Taro.showToast({
        title: '登录失败，请检查验证码是否正确',
        icon: 'none'
      });
    }finally{
      setIsLoginLoading(false);
    }
  };

  const userLoginApp = async () => {
    try {
      await getUserInfo().then((userInfoResponse) => {
        if (userInfoResponse.code === 200 && userInfoResponse.data) {
          console.log("更新用户信息:", userInfoResponse.data);
          setUserInfo({ ...userInfoResponse.data, updateTime: new Date().getTime() });
          Taro.showToast({
            title: '登录成功',
            icon: 'success'
          });
          routerBack(userInfoResponse.data);
        }else {
          Taro.showToast({
            title: '获取用户信息失败，请重试',
            icon: 'none'
          });
        }
      })
    } catch (error) {
      Taro.showToast({
        title: '登录出现错误，请重试',
        icon: 'none'
      });
    }
  }

  const getWechatUserInfo = async (e: any, sessionKey: string) => {
    console.log('微信登录按钮点击事件:', e);
    await getWechatUserInfoApi(e.encryptedData, e.iv, sessionKey).then((res: any) => {
      console.log('获取用户信息成功:', res);
      if (res.code == 200) {
        userLoginApp();
      }else {
        Taro.showToast({
          title: '微信信息解析失败，请重试',
          icon: 'none'
        });
      }
    }).catch(error => {
      console.error('获取用户信息失败:', error);
    });
  }

  /**
   * 提交注册表单
   */
  const handleRegister = async () => {
    // 表单验证
    if (!username) {
      setUsernameValid('请输入用户名');
      return;
    }
    setUsernameValid('');
    if (!/^1[0-9]\d{9}$/.test(phone)) {
      setPhoneValid('请输入11位有效手机号');
      return;
    }
    setPhoneValid('');
    if (!code) {
      setCodeValid('请输入验证码');
      return;
    }
    setCodeValid('');
    if (password.length < 6) {
      setPasswordValid('密码长度不能少于6位');
      return;
    }
    setPasswordValid('');
    if (password !== confirmPassword) {
      Taro.showToast({
        title: '两次输入的密码不一致',
        icon: 'none'
      });
      setConfirmPasswordValid('两次输入的密码不一致');
      return;
    }
    setConfirmPasswordValid('');

    try {
      setIsLoginLoading(true);
      const res = await registerUser({
        username,
        password,
        phone,
        code
      });
      if (res) {
        await userLoginApp();
      } else {
        Taro.showToast({
          title: '注册失败，请重试',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('注册失败:', error);
      Taro.showToast({
        title: '注册失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoginLoading(false);
    }
  };

  const handleCoachRegister = async () => {
    // 表单验证
    if (!/^1[0-9]\d{9}$/.test(phone)) {
      setPhoneValid('请输入11位有效手机号');
      return;
    }
    setPhoneValid('');
    if (!code) {
      setCodeValid('请输入验证码');
      return;
    }
    setCodeValid('');

    try {
      setIsLoginLoading(true);
      const res = await coachRegisterApi({
        phone,
        code
      });
      if (res) {
        if (res.code === 200) {
          Taro.redirectTo({
            url: `/pages/coach-register/index?phone=${phone}`
          });
        } else if (res.code === 20002) {
          Taro.showToast({
            title: '您已有教练账号，为您自动登录',
            icon: 'none'
          });
          await userLoginApp();
        } else if (res.code === 20003) {
          Taro.showToast({
            title: '您已注册为学员，无法注册为教练',
            icon: 'none'
          });
          setPageType("login")
        } else {
          Taro.showToast({
            title: res.message || '注册失败，请重试',
            icon: 'none'
          });
        }
      } else {
        Taro.showToast({
          title: '注册失败，请重试',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('注册失败:', error);
      Taro.showToast({
        title: '注册失败，请重试',
        icon: 'none'
      });
    } finally {
      setIsLoginLoading(false);
    }

  }

  const handleWechatLogin = async () => {
    if (Taro && typeof Taro.login === 'function') {
      await Taro.login(
        {
          success: res => {
            console.log('获取登录凭证成功:', res);
            wechatLogin(res.code).then(res => {
              console.log('微信登录成功:', res);
              if (res.code == 200) {
                if (res.data.access_token) {
                  getUserInfo().then((userInfoResponse) => {
                    if (userInfoResponse.code === 200 && userInfoResponse.data) {
                      console.log("更新用户信息");
                      setUserInfo({ ...userInfoResponse.data, updateTime: new Date().getTime() });
                      Taro.showToast({
                        title: '登录成功,欢迎您~',
                        icon: 'success'
                      });
                      routerBack(userInfoResponse.data);
                    }
                  })
                }else if (res.data.session_key){
                  Taro.showModal({
                    title: '登录身份确认',
                    content: '请选择您的登录身份',
                    confirmText: '学员登录',
                    cancelText: '教练登录',
                    cancelColor: '#1890ff',
                    confirmColor: '#ff4757',
                    success: async (modalRes) => {
                      if (modalRes.confirm) {
                        // 请求获取用户信息授权
                        Taro.showModal({
                          title: '授权登录',
                          content: '为了更好地为您提供服务，请授权获取您的微信头像和昵称',
                          success: async (modalResult) => {
                            if (modalResult.confirm) {
                              try {
                                // 获取用户信息
                                const userInfoRes = await Taro.getUserProfile({
                                  desc: '用于完善用户资料'
                                });
                                // 调用获取微信用户信息的方法
                                getWechatUserInfo(userInfoRes, res.data.session_key);
                              } catch (error) {
                                console.error('获取用户信息授权失败:', error);
                                Taro.showToast({
                                  title: '授权失败，请重试',
                                  icon: 'none'
                                });
                              }
                            }else {
                              Taro.showToast({
                                title: '未授权失败，头像昵称默认',
                                icon: 'none'
                              });
                            }
                    }});
                      } else {
                        Taro.redirectTo({
                          url: `/pages/coach-register/index?sessionKey=${encodeURIComponent(res.data.session_key)}`
                        });
                      }
                    }
                  });
                }else{
                  Taro.showToast({
                    title: '登录失败，请重试',
                    icon: 'error'
                  });
                }
              }
            });
          },
          fail: err => {
            console.error('获取登录凭证失败:', err);
            Taro.showToast({
              title: '获取登录凭证失败',
              icon: 'none'
            });
          }
        }
      )
    }
  };

  // 切换登录方式
  const handleLoginTypeChange = (type: 'phone' | 'password') => {
    setLoginType(type);
  };

// 导航到协议页面
  const navigateToAgreement = () => {
    Taro.navigateTo({
      url: '/pages/agreement/index',
    });
  };

// 导航到隐私页面
  const navigateToPrivacy = () => {
    Taro.navigateTo({
      url: '/pages/privacy/index',
    });
  };

  const loginPageContent = () => {
    return (
      <>
        <View className="login-header">
          <Text className="login-title text-lg">驾照易考通</Text>
        </View>
        <View className="login-type-switch">
          <Button 
            className={`type-button text-md ${loginType === 'phone' ? 'active' : ''}`} 
            onClick={() => handleLoginTypeChange('phone')}
          >
            验证码登录
          </Button>
          <Button 
            className={`type-button text-md ${loginType === 'password' ? 'active' : ''}`} 
            onClick={() => handleLoginTypeChange('password')}
          >
            密码登录
          </Button>
        </View>
        <View className="login-form">
          <View className="input-group">
            <Text className="input-label text-md"><Text className="required">*</Text>手机号</Text>
            <Input
              className="login-input text-lg"
              placeholder=""
              value={phone}
              focus={true}
              onInput={(e) => setPhone(e.detail.value)}
              type="number"
              maxlength={11}
            />
            {phoneValid && <Text className="input-hint">{phoneValid}</Text>}
          </View>

          {loginType === 'phone' ? (
            <View className="input-group">
              <Text className="input-label text-md"><Text className="required">*</Text>验证码</Text>
              <View className="code-input-wrapper">
                <Input
                  className="login-input text-lg code-input"
                  placeholder=""
                  value={code}
                  onInput={(e) => setCode(e.detail.value)}
                  type="number"
                  maxlength={6}
                />
                <View
                  className={`code-button text-lg ${isSendingCode ? 'disabled' : ''}`}
                  onClick={handleSendCode}
                >
                  {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                </View>
              </View>
              {codeValid && <Text className="input-hint">{codeValid}</Text>}
            </View>
          ):(
            <View className="input-group">
              <Text className="input-label"><Text className="required">*</Text>密码</Text>
              <Input
                className="login-input text-lg"
                placeholder=""
                value={password}
                onInput={(e) => setPassword(e.detail.value)}
                password
              />
              {passwordValid && <Text className="input-hint">{passwordValid}</Text>}
            </View>
          )}
          <Button className="login-button text-md" onClick={handleUserLogin} loading={isLoginLoading}>
            登录
          </Button>
        </View>
        <View className="wechat-login-section">
          <Text className="divider-text text-md">其他登录方式</Text>
          <Button 
            className="wechat-login-button text-md" 
            onClick={handleWechatLogin}>
            <Image
              className="wechat-icon" 
              src={`${IMAGE_BASE_URL}/public/images/wechat-icon.png`} 
              mode='aspectFit' />
            微信一键登录
          </Button>
        </View>
      </>
    )
  }

  const registerPageContent = () => {
    return (
      <>
        <View className="login-header">
          <Text className="register-subtitle text-lg">加入我们 驾照易考通</Text>
        </View>
        <View className="register-form-container">
          <View className="custom-tabs">
            <View className="tabs-header">
              <View
                key="student"
                className={`tabs-tab ${registerType === "student" ? 'tabs-tab-active' : ''}`}
                onClick={() => setRegisterType("student")}
              >
                <Text>学员注册</Text>
              </View>
              <View
                key="coach"
                className={`tabs-tab ${registerType === "coach" ? 'tabs-tab-active' : ''}`}
                onClick={() => setRegisterType("coach")}
              >
                <Text>教练注册</Text>
              </View>
            </View>
            <View className="tabs-content">
              {registerType == "student" && (
                <View>
                  <View className="register-form">
                    {/* 用户名输入 */}
                    <View className="input-group">
                      <Text className="input-label text-md"><Text className="required">*</Text>用户名</Text>
                      <Input
                        className="login-input text-lg"
                        placeholder=""
                        value={username}
                        focus={true}
                        onInput={(e) => setUsername(e.detail.value)}
                      />
                      {usernameValid && <Text className="input-hint">{usernameValid}</Text>}
                    </View>

                    {/* 手机号输入 */}
                    <View className="input-group">
                      <Text className="input-label text-md"><Text className="required">*</Text>手机号</Text>
                      <Input
                        className="login-input text-lg"
                        placeholder=""
                        type="number"
                        value={phone}
                        onInput={(e) => setPhone(e.detail.value)}
                      />
                      {phoneValid && <Text className="input-hint">{phoneValid}</Text>}
                    </View>

                    {/* 验证码输入 */}
                    <View className="input-group">
                      <Text className="input-label text-md"><Text className="required">*</Text>验证码</Text>
                      <View className="code-input-wrapper">
                        <Input
                          className="login-input text-lg code-input"
                          placeholder=""
                          value={code}
                          onInput={(e) => setCode(e.detail.value)}
                          type="number"
                          maxlength={6}
                        />
                        <View
                          className={`code-button text-base ${isSendingCode ? 'disabled' : ''}`}
                          onClick={handleSendCode}
                        >
                          {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                        </View>
                      </View>
                      {codeValid && <Text className="input-hint">{codeValid}</Text>}
                    </View>

                    {/* 密码输入 */}
                    <View className="input-group">
                      <Text className="input-label text-md"><Text className="required">*</Text>设置密码</Text>
                      <Input
                        className="login-input text-lg"
                        placeholder=""
                        password
                        value={password}
                        onInput={(e) => setPassword(e.detail.value)}
                      />
                      {passwordValid && <Text className="input-hint">{passwordValid}</Text>}
                    </View>

                    {/* 确认密码输入 */}
                    <View className="input-group">
                      <Text className="input-label text-md"><Text className="required">*</Text>确认密码</Text>
                      <Input
                        className="login-input text-lg"
                        placeholder=""
                        password
                        value={confirmPassword}
                        onInput={(e) => setConfirmPassword(e.detail.value)}
                      />
                      {confirmPasswordValid && <Text className="input-hint">{confirmPasswordValid}</Text>}
                    </View>

                    {/* 注册按钮 */}
                    <Button
                      className="login-button text-lg"
                      onClick={handleRegister}
                    >
                      注册
                    </Button>
                  </View>
                </View>
              )}
              {registerType == "coach" && (
                <View>
                  <View className="register-form">
                    <View className="input-group">
                      <Text className="input-label text-md"><Text className="required">*</Text>手机号</Text>
                      <Input
                        className="login-input text-md"
                        placeholder=""
                        type="number"
                        value={phone}
                        onInput={(e) => setPhone(e.detail.value)}
                      />
                      {phoneValid && <Text className="input-hint">{phoneValid}</Text>}
                    </View>
                    <View className="input-group">
                      <Text className="input-label text-md"><Text className="required">*</Text>验证码</Text>
                      <View className="code-input-wrapper">
                        <Input
                          className="login-input text-lg code-input"
                          placeholder=""
                          value={code}
                          onInput={(e) => setCode(e.detail.value)}
                          type="number"
                          maxlength={6}
                        />
                        <View
                          className={`code-button text-lg ${isSendingCode ? 'disabled' : ''}`}
                          onClick={handleSendCode}
                        >
                          {countdown > 0 ? `${countdown}秒后重试` : '获取验证码'}
                        </View>
                      </View>
                      {codeValid && <Text className="input-hint">{codeValid}</Text>}
                    </View>

                    <Button
                      className="login-button text-md"
                      onClick={handleCoachRegister}
                    >
                      注册
                    </Button>
                  </View>
                </View>
              )}
            </View>
          </View>
        </View>
      </>
    )
  }

  return (
    <View className="login-container" style={{backgroundImage: `url(${IMAGE_BASE_URL}/public/images/login-bg.png)`}}>
      <View className="login-content">
        {pageType == 'login' ? loginPageContent() : registerPageContent()}

        <View className="register-section">
          <Text className="text-md">{pageType == 'login' ? '还没有账号？' : '已有账号？'}</Text>
          <Text className="register-link text-md" onClick={() => setPageType(pageType == 'login' ? 'register' : 'login')}>
            {pageType == 'login' ? '立即注册' : '登录'}
          </Text>
        </View>

        <View className="login-tips text-xs">
          <Text>{pageType == 'login' ? '登录' : '注册'}即表示您同意我们的
            <Text className="tip-link" onClick={navigateToAgreement}>用户协议</Text>和
            <Text className="tip-link" onClick={navigateToPrivacy}>隐私政策</Text>
          </Text>
        </View>
      </View>
    </View>
  );
};

export default LoginPage;